package com.gljx.web.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gljx.util.ActitiviUtil;
import com.gljx.web.Entity.*;
import com.gljx.web.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gljx.util.GetFid;
import com.gljx.web.dao.CommonDao;
import com.gljx.web.dao.MaintainItemEditEntryMapper;
import com.gljx.web.dao.MaintainItemEditMapper;
import com.gljx.web.dao.MaintainItemMapper;
import com.gljx.web.service.MaintainItemEditService;

@Service
@Transactional
public class MaintainItemEditServiceImpl extends CommonDao implements MaintainItemEditService{

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	@Autowired
	private MaintainItemEditMapper maintainItemEditMapper;
	@Autowired
	private MaintainItemEditEntryMapper maintainItemEditEntryMapper;
	@Autowired
	private MaintainItemMapper maintainItemMapper;

	@Autowired
	private MessageService messageService;
	
	/**
	 *取分页数据 
	 *@param pindex 页码
	 *@param psql SQL语句，需要带 rownum rn 例如：select rownum rn,t.* from zzda t
	 *@param psize 每页记录数
	 * */
	@Override
	public Map<String, Object> selectPage(int pindex, String psql, int psize) {
		  Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("Pindex", pindex);
	       paramMap.put("Psql", psql);
	       paramMap.put("Psize", psize);
	       paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
	       paramMap.put("v_cur", oracle.jdbc.OracleTypes.CURSOR);
	       this.getSqlSession().select("com.gljx.web.dao.MaintainItemEditMapper.pagemap", paramMap, null);
	       return  paramMap;
	}

	/**
	 * 取记录总数      dmz 20160921
	 * @param psql   SQL语句
	 * @return
	 */
	@Override
	public Map<String, Object> selectPageCount(String psql) {
		   Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("Psql", psql);
	       paramMap.put("Pcount", oracle.jdbc.OracleTypes.INTEGER);
	       this.getSqlSession().select("com.gljx.web.dao.MaintainItemEditMapper.pagecount", paramMap, null);
	       return paramMap;
	}

	/**
	 * 根据条件查询子类信息
	 */
	@Override
	public List<MaintainItemEditEntry> queryMaintainItemEditEntry(String faprentId, String maintainItemName) {
		// TODO Auto-generated method stub
		   Map<String, Object> paramMap = new HashMap<String, Object>();
	       paramMap.put("v_fparentid", faprentId);
	       paramMap.put("v_maintainItemName", maintainItemName);
	       paramMap.put("v_cursor", oracle.jdbc.OracleTypes.CURSOR);
	       this.getSqlSession().select("com.gljx.web.dao.MaintainItemEditEntryMapper.selectMaintainItemEditEntry", paramMap, null);
	       @SuppressWarnings("unchecked")
	       List<MaintainItemEditEntry> maintainItemEditEntrys = (List<MaintainItemEditEntry>) paramMap.get("v_cursor");
	       return maintainItemEditEntrys;
	}

	/**
	 * 添加或修改
	 */
	@Override
	public void editMaintainItemEdit(MaintainItemEdit maintainItemEdit, String[] fseq, String[] cfmaintainitemno,
			String[] cfmaintainitemid, String[] cfmaintainitemgs, String[] cfmaintainitemdj, String[] cfmaintainitembxq,
			String[] cfmigs, String[] cfmidj, String[] cfmibxq, String[] cfdesc, User user, String time) {
		// TODO Auto-generated method stub
		if("".equals(maintainItemEdit.getFid()) || maintainItemEdit.getFid() == null){
			//创建人id
			maintainItemEdit.setFcreatorid(user.getFid());
			//利用UUID生成fid
			maintainItemEdit.setFid(GetFid.UUIDIntoFid());
			//当前时间
			maintainItemEdit.setFcreatetime(time);
			//状态
            maintainItemEdit.setCfbillstate(3L);
            //添加
			maintainItemEditMapper.insertSelective(maintainItemEdit);
		}else{
			//修改时间时间
			maintainItemEdit.setFlastupdatetime(time);
			//修改人id
			maintainItemEdit.setFlastupdateuserid(user.getFid());
			//修改
			maintainItemEditMapper.updateByPrimaryKeySelective(maintainItemEdit);
			//先删除子类信息
			maintainItemEditEntryMapper.deleteByFparentId(maintainItemEdit.getFid());
		}
		//添加子类
		List<MaintainItemEditEntry> maintainItemEditEntrys = new ArrayList<>();
		if(fseq == null || fseq.length == 0){
			
		}else{
			for (int i = 0; i < fseq.length; i++) {
				MaintainItemEditEntry maintainItemEditEntry = new MaintainItemEditEntry();
				maintainItemEditEntry.setCfmaintainitemno(cfmaintainitemno[i]);
				maintainItemEditEntry.setCfmaintainitemid(cfmaintainitemid[i]);
				if("".equals(cfmaintainitemgs[i])){
					
				}else{
					maintainItemEditEntry.setCfmaintainitemgs(new BigDecimal(cfmaintainitemgs[i]));
				}
				if("".equals(cfmaintainitemdj[i])){
					
				}else{
					maintainItemEditEntry.setCfmaintainitemdj(new BigDecimal(cfmaintainitemdj[i]));
				}
				maintainItemEditEntry.setCfmaintainitembxq(cfmaintainitembxq[i]);
				if("".equals(cfmigs[i])){
					
				}else{
					maintainItemEditEntry.setCfmigs(new BigDecimal(cfmigs[i]));
				}
				if("".equals(cfmidj[i])){
					
				}else{
					maintainItemEditEntry.setCfmidj(new BigDecimal(cfmidj[i]));
				}
				maintainItemEditEntry.setCfmibxq(cfmibxq[i]);
				maintainItemEditEntry.setCfdesc(cfdesc[i]);
				maintainItemEditEntry.setFseq((long)i+1);
				maintainItemEditEntry.setFid(GetFid.UUIDIntoFid());
				maintainItemEditEntry.setFparentid(maintainItemEdit.getFid());
				maintainItemEditEntrys.add(maintainItemEditEntry);
			}
			maintainItemEditEntryMapper.insertMaintainItemEditEntry(maintainItemEditEntrys);
		}
	}

	/**
	 * 根据fid查询
	 */
	@Override
	public MaintainItemEdit queryMaintainItemEditByFid(String fid) {
		// TODO Auto-generated method stub
		return maintainItemEditMapper.selectMaintainItemEditByFid(fid);
	}

	/**
	 * 根据fid删除
	 */
	@Override
    public void deleteMaintainItemEditByFid(String fid, String[] deleteId, String[] fnumber, String fnumber2) {
        // TODO Auto-generated method stub
		if(fid == null || "".equals(fid)){
            /*//先删除子类信息
            maintainItemEditEntryMapper.deleteByArray(deleteId);
			//在删除父类信息
			maintainItemEditMapper.deleteByArray(deleteId);*/
            for (int i = 0; i < deleteId.length; i++) {
                //先删除子类信息
                maintainItemEditEntryMapper.deleteByFparentId(deleteId[i]);
                //在删除父类信息
                maintainItemEditMapper.deleteByPrimaryKey(deleteId[i]);
                //删除流程
                activitiUtil.deleteTask("maintainItemEdit", fnumber[i]);
            }
		}else{
			//先删除子类信息
			maintainItemEditEntryMapper.deleteByFparentId(fid);
			//在删除父类信息
			maintainItemEditMapper.deleteByPrimaryKey(fid);
            //删除流程
            activitiUtil.deleteTask("maintainItemEdit", fnumber2);
        }
	}

	/**
	 * 审核，反审核
	 */
	@Override
	public int auditMaintainItemEdit(String fid, String type, String fhandlerId, String fnumber, String message, String state, String auditState) {
		// TODO Auto-generated method stub
		MaintainItemEdit maintainItemEdit = new MaintainItemEdit();
		String message2;
		if ("1".equals(type)) {
			if ("".equals(message)) {
				if ("1".equals(state)) {
					message2 = "同意";
				} else {
					message2 = "不同意";
				}
			} else {
				if ("1".equals(state)) {
					message2 = "同意:" + message;
				} else {
					message2 = "不同意：" + message;
				}
			}
			//VariableName  流程变量名称  fnumber 单据；state 状态 同意，不同意，前段传来的备注
			Object returnMsg = activitiUtil.auditComplteMessage("maintainItemEdit", fnumber, Integer.valueOf(state), message2);
			if (returnMsg instanceof Message) {
				Message resultMsg = (Message) returnMsg;
				resultMsg.setMessage("修改维修项目-审核 #" + fnumber + " #");//消息内容
				resultMsg.setUrl("/queryMaintainItemEditByFid?fid=" + fid + "");//详细路径
				messageService.insert(resultMsg);
				//判断是否同意,如果不同意,修改状态
				if (!"1".equals(state)) {
					//fid
					maintainItemEdit.setFid(fid);
					//状态
					maintainItemEdit.setCfbillstate(3L);
					//修改
					maintainItemEditMapper.updateByPrimaryKeySelective(maintainItemEdit);
				}
				return 0;
			} else if (activitiUtil.notAssign.equals(returnMsg)) {
				System.out.println("当前用户不是要求的经办人");
				return 3;
			} else if (activitiUtil.FINISH.equals(returnMsg)) {
				System.out.println("此流程成功推进,并且此流程已经结束");
				maintainItemEdit.setCfbillstate(5L);
				//fid
				maintainItemEdit.setFid(fid);
				//审核人id
				maintainItemEdit.setFauditorid(fhandlerId);
				//修改人
				maintainItemEdit.setFlastupdateuserid(fhandlerId);
                //反审核意见
                maintainItemEdit.setFdescription(message);
                //查询子类信息
				List<MaintainItemEditEntry> maintainItemEditEntrys = queryMaintainItemEditEntry(fid, "");
				for (MaintainItemEditEntry maintainItemEditEntry : maintainItemEditEntrys) {
					//维修项目id
					String wxxmid = maintainItemEditEntry.getCfmaintainitemid();
					//修改后工时
					BigDecimal xghgs = maintainItemEditEntry.getCfmigs();
					//修改后单价
					BigDecimal xghdj = maintainItemEditEntry.getCfmidj();
					//修改保修期
					Object xghbxq = maintainItemEditEntry.getCfmibxq();
					//修改维修项目
					if (wxxmid == null || "".equals(wxxmid)) {

					} else {
						if (xghgs == null && xghdj == null && xghbxq == null) {

						} else {
							MaintainItem maintainItem = new MaintainItem();
							maintainItem.setFid(wxxmid);
							maintainItem.setFsimplename(xghbxq);
							maintainItem.setCfprice(xghdj);
							maintainItem.setCfmanhours(xghgs);
							maintainItemMapper.updateMaintainItem(maintainItem);
						}
					}
				}
				return maintainItemEditMapper.updateByPrimaryKeySelective(maintainItemEdit);
			} else if (activitiUtil.SUCCESS.equals(returnMsg)) {
				//判断是否同意,如果不同意,修改状态
				if (!"1".equals(state)) {
					//fid
					maintainItemEdit.setFid(fid);
					//状态
					maintainItemEdit.setCfbillstate(3L);
					//修改
					maintainItemEditMapper.updateByPrimaryKeySelective(maintainItemEdit);
				}
				System.out.println("此流程成功推进.");
				return 0;
			} else if (activitiUtil.notTask.equals(returnMsg)) {
				System.out.println("没有找到正在进行的相关流程");
				return 2;
			}
		}else{
			if ("endTrue".equals(auditState)) {
				Message message21 = activitiUtil.getMessage("maintainItemEdit", fnumber);
				if (message21 != null) {
					message21.setMessage("修改维修项目-反审核 #" + fnumber + " #");//消息内容
					message21.setUrl("/queryMaintainItemEditByFid?fid=" + fid + "");//详细路径
					messageService.insert(message21);
				}
			} else {
				Object result = activitiUtil.jumpActivtiMessage("maintainItemEdit", fnumber, message);
				if (result instanceof Message) {
					Message resultMsg = (Message) result;
					resultMsg.setMessage("修改维修项目-反审核" + fnumber + " #");//消息内容
					resultMsg.setUrl("/queryMaintainItemEditByFid?fid=" + fid + "");//详细路径
					messageService.insert(resultMsg);
				}
			}
			//fid
			maintainItemEdit.setFid(fid);
			//审核人id
			maintainItemEdit.setFauditorid(fhandlerId);
			//修改人
			maintainItemEdit.setFlastupdateuserid(fhandlerId);
			//状态
			maintainItemEdit.setCfbillstate(3L);
			return maintainItemEditMapper.updateByPrimaryKeySelective(maintainItemEdit);
		}
		return 0;
	}

    @Override
    public int modifyMaintainItemEdit(MaintainItemEdit maintainItemEdit) {
        return maintainItemEditMapper.updateByPrimaryKeySelective(maintainItemEdit);
    }

    @Override
    public List<MaintainItemEditEntry> selectMaintainItemEditByInfo(String fcompanyid, String maintainItemName, String fnumber, String beginTime, String endTime) {
        Map<String, String> map = new HashMap<>();
        map.put("fcompanyid", fcompanyid);
        map.put("maintainItemName", maintainItemName);
        map.put("fnumber", fnumber);
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        return maintainItemEditEntryMapper.selectMaintainItemEditByInfo(map);
    }

}
